﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var master = Master as SiteMaster;
        if (master != null)
        {
            master.AccionesIniciales();
        }


    }


    protected void Button1_OnClick(object sender, EventArgs e)
    {
        //Checar el login del usuario
        var user = UserName.Text.Trim();
        var pass = Password.Text.Trim();

        if (LoginUser(user, pass))
        {
            redirect();
        }
    }

    protected void redirect()
    {
        var rol = (Int32)Page.Session["rol"];
        switch (rol)
        {
            case 1:
                Response.Redirect("Jefe.aspx");
                break;
            case 2:
                Response.Redirect("Usuario.aspx");
                break;
            case 3:
                Response.Redirect("Empleados.aspx");
                break;
            case 4:
                Response.Redirect("Nuevo.aspx");
                break;
        }
    }


    private void EnviarReporteAJefes()
    {

        //verificar ultima fecha de envio
        DateTime ultimaFecha = DateTime.Now;
        var query = "SELECT * FROM ultimaFecha WHERE id = '0'";
        var myConnection = new MySqlConnection();
        myConnection.ConnectionString = "Persist Security Info=False;Username=root;Password=;database=helpdeskdb;server=localhost;Connect Timeout=30";
        myConnection.Open();
        var cmd = new MySqlCommand(query, myConnection);
        cmd.ExecuteNonQuery();
        var dataReader = cmd.ExecuteReader();
        while (dataReader.Read())
        {
            ultimaFecha = (DateTime)dataReader["fecha"];
        }
        dataReader.Close();
        myConnection.Close();
        
        //si no han pasado mas de 5 dias desde la ultima fecha en que se hizo la entrega de reportes
        // se aborta el procedimiento
        var ahora = DateTime.Now;
        if (ahora.Subtract(ultimaFecha).Days < 5)
            return;

        var userManager = new UsersManager();
        var mailManager = new MailManager();
        var servicioSolicitudes = new SolicitudesManager();

        //obtener a todos los jefes
        var jefes = userManager.ObtenerJefes();
        foreach (var jefeId in jefes)
        {
            //obtener solicitudes de cada jefe
            var solicitudes = servicioSolicitudes.ObtenerSolicitudes(jefeId);
            var textoMail = new StringBuilder();
            foreach (var solicitud in solicitudes)
            {
                textoMail.Append(solicitud);
            }

            var mail = new Mail
                   {
                       Asunto = "Reporte de solicitudes para jefes",
                       Contenido = textoMail.ToString(),
                       FechaEnvio = new DateTime(),
                       De = "HelpDeskPlus@itesm.mx",
                       Para = userManager.ObtenerMail(long.Parse(jefeId)),
                       DeId = 0,
                       ParaId = long.Parse(jefeId)
                   };


            mailManager.MandarMail(mail);
        }

        //actualizar ultima fecha de envio
        query = "UPDATE `ultimaFecha` set fecha = NOW()";
        myConnection = new MySqlConnection();
        myConnection.ConnectionString = "Persist Security Info=False;Username=root;Password=;database=helpdeskdb;server=localhost;Connect Timeout=30";
        myConnection.Open();
        cmd = new MySqlCommand(query, myConnection);
        cmd.ExecuteNonQuery();
        myConnection.Close();

    }


    private bool LoginUser(string user, string pass)
    {
        var sesionIniciada = false;
        var query = String.Format("SELECT * FROM usuarios WHERE nombre = '{0}' and password = '{1}'", user, pass);
        var conexion = new MySqlConnection
                               {
                                   ConnectionString =
                                       "Persist Security Info=False;Username=root;Password=;database=helpdeskdb;server=localhost;Connect Timeout=30"
                               };
        conexion.Open();

        //create command and assign the query and connection from the constructor
        var cmd = new MySqlCommand(query, conexion);
        cmd.ExecuteNonQuery();

        var dataReader = cmd.ExecuteReader();
        if (dataReader.HasRows)
        {
            sesionIniciada = true;
            while (dataReader.Read())
            {
                Page.Session["user"] = user;
                Page.Session["userId"] = dataReader["usuarios_id"];
                Page.Session["rol"] = dataReader["rol"];
            }
        }

        dataReader.Close();
        conexion.Close();

        return sesionIniciada;
    }
}